package org.example.rowing.service;

import lombok.extern.slf4j.Slf4j;
import org.example.rowing.domain.RoundScore;
import org.example.rowing.domain.Team;
import org.example.rowing.vo.RaceVO;
import org.example.rowing.vo.RegistrationVO;
import org.example.rowing.vo.RoundScoreVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class CKProcessFortySixToFiftyFourBoatsService implements RaceProcessStrategy {

    @Autowired
    private RaceInfoService raceInfoService;
    @Autowired
    private RaceProcessCommonService raceProcessCommonService;

    public static final List<String> teamLanes = Arrays.asList("",
            "A组5号", "A组4号", "A组6号", "A组3号", "A组7号", "A组2号", "A组8号", "A组1号", "A组9号",
            "B组5号", "B组4号", "B组6号", "B组3号", "B组7号", "B组2号", "B组8号", "B组1号", "B组9号",
            "C组5号", "C组4号", "C组6号", "C组3号", "C组7号", "C组2号", "C组8号", "C组1号", "C组9号",
            "D组5号", "D组4号", "D组6号", "D组3号", "D组7号", "D组2号", "D组8号", "D组1号", "D组9号",
            "E组5号", "E组4号", "E组6号", "E组3号", "E组7号", "E组2号", "E组8号", "E组1号", "E组9号",
            "F组5号", "F组4号", "F组6号", "F组3号", "F组7号", "F组2号", "F组8号", "F组1号", "F组9号"
    );

    /**
     * 获取预赛晋级决赛的列表
     * @param curList
     */
    public void getAdvancingToFinals(List<RoundScoreVO> curList, Long raceId) {}

    /**
     * 获取预赛晋级半决赛的列表
     * @param curList
     * @param raceId
     * @return
     */
    public void getAdvancingToHalfFinals(List<RoundScoreVO> curList, Long raceId) {
        List<RoundScoreVO> advancingToHalfA = new ArrayList<>();
        List<RoundScoreVO> advancingToHalfB = new ArrayList<>();
        List<RoundScoreVO> advancingToHalfC = new ArrayList<>();
        List<RoundScoreVO> groupAList = new ArrayList<>();
        List<RoundScoreVO> groupBList = new ArrayList<>();
        List<RoundScoreVO> groupCList = new ArrayList<>();
        List<RoundScoreVO> groupDList = new ArrayList<>();
        List<RoundScoreVO> groupEList = new ArrayList<>();
        List<RoundScoreVO> groupFList = new ArrayList<>();

        // 1. 按预赛组别（A/B/C 组）分组
        for (RoundScoreVO vo : curList) {
            String lane = vo.getLane();
            if (lane != null) {
                if (lane.startsWith("A组")) {
                    groupAList.add(vo);
                } else if (lane.startsWith("B组")) {
                    groupBList.add(vo);
                } else if (lane.startsWith("C组")) {
                    groupCList.add(vo);
                } else if (lane.startsWith("D组")) {
                    groupDList.add(vo);
                } else if (lane.startsWith("E组")) {
                    groupEList.add(vo);
                } else if (lane.startsWith("F组")) {
                    groupFList.add(vo);
                }
            }
        }

        // 2. 对每组按成绩排序（假设升序排列，成绩越小越好）
        raceProcessCommonService.sortedEntries(groupAList); // 排序后索引0为第1名（晋级决赛A）
        raceProcessCommonService.sortedEntries(groupBList);
        raceProcessCommonService.sortedEntries(groupCList);
        raceProcessCommonService.sortedEntries(groupDList);
        raceProcessCommonService.sortedEntries(groupEList);
        raceProcessCommonService.sortedEntries(groupFList);

        // 3. 收集每组 1-6 名
        allocateByFlag(groupAList, advancingToHalfA, advancingToHalfB, advancingToHalfC);
        allocateByFlag(groupBList, advancingToHalfB, advancingToHalfC, advancingToHalfA);
        allocateByFlag(groupCList, advancingToHalfC, advancingToHalfA, advancingToHalfB);
        allocateByFlag(groupDList, advancingToHalfA, advancingToHalfB, advancingToHalfC);
        allocateByFlag(groupEList, advancingToHalfB, advancingToHalfC, advancingToHalfA);
        allocateByFlag(groupFList, advancingToHalfC, advancingToHalfA, advancingToHalfB);

        // 4. 组内排序
        List<RoundScoreVO> tempList = new ArrayList<>();
        tempList.add(groupAList.get(4));
        tempList.add(groupBList.get(4));
        tempList.add(groupCList.get(4));
        tempList.add(groupDList.get(4));
        tempList.add(groupEList.get(4));
        tempList.add(groupFList.get(4));
        raceProcessCommonService.sortedEntries(tempList);
        raceProcessCommonService.sortedEntries(advancingToHalfA);
        raceProcessCommonService.sortedEntries(advancingToHalfB);
        raceProcessCommonService.sortedEntries(advancingToHalfC);
        advancingToHalfA.add(tempList.get(0));
        advancingToHalfB.add(tempList.get(1));
        advancingToHalfC.add(tempList.get(2));

        // 5. 更新半决赛A
        for (int i = 0; i < advancingToHalfA.size(); i++) {
            RegistrationVO registrationVO = advancingToHalfA.get(i).getRegistrationVO();
            // 保存用户输入的分数
            RoundScoreVO roundScore = new RoundScoreVO(raceId, registrationVO, "半决赛", null, teamLanes.get(i + 1), null);
            raceInfoService.saveRoundScore(roundScore);
        }

        // 6. 更新半决赛B
        for (int i = 0; i < advancingToHalfB.size(); i++) {
            RegistrationVO registrationVO = advancingToHalfB.get(i).getRegistrationVO();
            // 保存用户输入的分数
            RoundScoreVO roundScore = new RoundScoreVO(raceId, registrationVO, "半决赛", null, teamLanes.get(i + 10), null);
            raceInfoService.saveRoundScore(roundScore);
        }

        // 7. 更新半决赛C
        for (int i = 0; i < advancingToHalfC.size(); i++) {
            RegistrationVO registrationVO = advancingToHalfC.get(i).getRegistrationVO();
            // 保存用户输入的分数
            RoundScoreVO roundScore = new RoundScoreVO(raceId, registrationVO, "半决赛", null, teamLanes.get(i + 19), null);
            raceInfoService.saveRoundScore(roundScore);
        }
    }

    /**
     *
     * @param group 预赛组
     * @param halfA 半决赛A组列表
     * @param halfB 半决赛B组列表
     */
    private void allocateByFlag(List<RoundScoreVO> group, List<RoundScoreVO> halfA, List<RoundScoreVO> halfB, List<RoundScoreVO> halfC) {
        int startIndex = 0; // 第1名（索引0）
        int endIndex = Math.min(group.size(), 4); // 最多取到第4名（索引5）

        for (int i = startIndex; i < endIndex; i++) {
            if (i % 3 == 0) { // 0 3
                halfA.add(group.get(i));
            } else if (i % 3 == 1) { // 1
                halfB.add(group.get(i));
            } else { // 2
                halfC.add(group.get(i));
            }
        }
    }

    /**
     * 获取半决赛晋级决赛的列表
     * @param curList
     * @param raceId
     */
    public void getHalfFinalsToFinals(List<RoundScoreVO> curList, Long raceId) {
        List<RoundScoreVO> advancingToFinaA = new ArrayList<>();
        List<RoundScoreVO> advancingToFinaB = new ArrayList<>();
        List<RoundScoreVO> advancingToFinaC = new ArrayList<>();
        List<RoundScoreVO> groupAList = new ArrayList<>();
        List<RoundScoreVO> groupBList = new ArrayList<>();
        List<RoundScoreVO> groupCList = new ArrayList<>();

        for (RoundScoreVO vo : curList) {
            String lane = vo.getLane();
            if (lane != null) {
                if (lane.startsWith("A组")) {
                    groupAList.add(vo);
                } else if (lane.startsWith("B组")) {
                    groupBList.add(vo);
                } else if (lane.startsWith("C组")) {
                    groupCList.add(vo);
                }
            }
        }

        raceProcessCommonService.sortedEntries(groupAList);
        raceProcessCommonService.sortedEntries(groupBList);
        raceProcessCommonService.sortedEntries(groupCList);

        // 更新决赛A
        for (int i = 0; i < 3; i++) {
            advancingToFinaA.add(groupAList.get(i));
            advancingToFinaA.add(groupBList.get(i));
            advancingToFinaA.add(groupCList.get(i));
        }
        raceProcessCommonService.sortedEntries(advancingToFinaA);
        for (int i = 0; i < advancingToFinaA.size(); i++) {
            RegistrationVO registrationVO = advancingToFinaA.get(i).getRegistrationVO();
            // 保存用户输入的分数
            RoundScoreVO roundScore = new RoundScoreVO(raceId, registrationVO, "决赛", null, teamLanes.get(i + 1), null);
            raceInfoService.saveRoundScore(roundScore);
        }

        // 更新决赛B
        for (int i = 3; i < 6; i++) {
            advancingToFinaB.add(groupAList.get(i));
            advancingToFinaB.add(groupBList.get(i));
            advancingToFinaB.add(groupCList.get(i));
        }
        raceProcessCommonService.sortedEntries(advancingToFinaB);
        for (int i = 0; i < advancingToFinaB.size(); i++) {
            RegistrationVO registrationVO = advancingToFinaB.get(i).getRegistrationVO();
            // 保存用户输入的分数
            RoundScoreVO roundScore = new RoundScoreVO(raceId, registrationVO, "决赛", null, teamLanes.get(i + 10), null);
            raceInfoService.saveRoundScore(roundScore);
        }

        // 更新决赛C
        for (int i = 6; i < 9; i++) {
            advancingToFinaC.add(groupAList.get(i));
            advancingToFinaC.add(groupBList.get(i));
            advancingToFinaC.add(groupCList.get(i));
        }
        raceProcessCommonService.sortedEntries(advancingToFinaC);
        for (int i = 0; i < advancingToFinaC.size(); i++) {
            RegistrationVO registrationVO = advancingToFinaC.get(i).getRegistrationVO();
            // 保存用户输入的分数
            RoundScoreVO roundScore = new RoundScoreVO(raceId, registrationVO, "决赛", null, teamLanes.get(i + 19), null);
            raceInfoService.saveRoundScore(roundScore);
        }
    }

    /**
     * 获取最终排名
     * @param curList
     * @param raceVO
     * @return
     */
    public List<RoundScoreVO> getRank(List<RoundScoreVO> curList, RaceVO raceVO) {
        List<RoundScoreVO> groupAList = new ArrayList<>();
        List<RoundScoreVO> groupBList = new ArrayList<>();
        List<RoundScoreVO> groupCList = new ArrayList<>();

        for (RoundScoreVO vo : curList) {
            String lane = vo.getLane();
            if (lane != null) {
                if (lane.startsWith("A组")) {
                    groupAList.add(vo);
                } else if (lane.startsWith("B组")) {
                    groupBList.add(vo);
                } else if (lane.startsWith("C组")) {
                    groupCList.add(vo);
                }
            }
        }
        raceProcessCommonService.sortedEntries(groupAList);
        raceProcessCommonService.sortedEntries(groupBList);
        raceProcessCommonService.sortedEntries(groupCList);
        groupAList.addAll(groupBList);
        groupAList.addAll(groupCList);

        saveFinalResult(groupAList, raceVO);
        int i = 0;
        for (RoundScoreVO roundScoreVO : groupAList) {
            Double v = Double.valueOf(i++);
            RoundScore roundScore = new RoundScore(raceVO.getId(), "比赛结果", null, null, v, roundScoreVO.getRegistrationVO().getRegistrationId(), roundScoreVO.getStatus());
            raceInfoService.saveRoundScore(roundScore);
        }
        return groupAList;
    }

    private void saveFinalResult(List<RoundScoreVO> finalList, RaceVO raceVO) {
        raceProcessCommonService.saveFinalResult(finalList, raceVO);
    }
}
